package net.aiion.weave.util.net;

public final class URLDecoder implements Decoder
{
    private static final Decoder DECODER_INSTANCE = new URLDecoder();

    private URLDecoder() {
    }

    @Override
    public String decode(final String aEncodedString) {
        // Source: http://www.ietf.org/rfc/rfc1738.txt
        final StringBuilder decodedString = new StringBuilder();
        for (int i = 0; i < aEncodedString.length(); i++) {
            final char c = aEncodedString.charAt(i);
            switch (c) {
            case '%':
                if (aEncodedString.length() - i < 0) {
                    throw new DecodingException("Not enough characters left for decoding the encoded character");
                } else {
                    decodedString.append((char) Integer.parseInt(new String(new char[] {
                        aEncodedString.charAt(i + 1), aEncodedString.charAt(i + 2)
                    }), 16));
                    i += 2;
                }
                break;
            case '+':
                decodedString.append(' ');
                break;
            default:
                decodedString.append(c);
                break;
            }
        }
        return decodedString.toString();
    }

    public static Decoder getInstance() {
        return DECODER_INSTANCE;
    }
}
